package cn.zl.common.utils;

import cn.zl.common.properties.BlogProperties;
import cn.zl.common.properties.ShiroProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Shiro 加密工具
 * 将明文密码进行MD5加密
 * @author zl
 * @date 2023/9/12
 */
@Component
public class Md5Util {

    @Resource
    private BlogProperties properties;

    /**
     * 算法名称
     */
    private static final String ALGORITH_NAME = "MD5";

    /**
     * 迭代次数
     */
    private static final int HASH_ITERATIONS = 2;

    /**
     * Shiro 加密
     *
     * @param password 明文密码
     * @return 加密后的密码
     * @value shiro.getCipherKey() 加密混用的盐值
     */
    public String encryptPassword(String password) {
        ShiroProperties shiro = properties.getShiro();
        if (password == null) {
            return null;
        }
        return new SimpleHash(
                ALGORITH_NAME,
                StringUtils.lowerCase(StringUtils.lowerCase(password)),/*转换为小写*/
                shiro.getCipherKey(),/*加密混用的盐值*/
                HASH_ITERATIONS).toHex();/*将加密后的密码以十六进制字符串形式返回*/
    }
}
